<template>
  <div style="height: calc(100vh - 100px)">
    <el-card>
      <div class="flow-box" v-loading="loading">
        <el-button @click="goBack" class="button-back">
          <span>返 回</span>
        </el-button>
        <el-button type="primary" @click="saveSet" class="button-publish">
          <span>保 存</span>
        </el-button>
        <span v-if="isDisabled" class="span-tip"
          >您不是该流程管理员，无权限编辑该流程。</span
        >
        <div class="fd-nav-content">
          <section class="dingflow-design">
            <div class="zoom">
              <div
                class="zoom-out"
                :class="nowVal == 50 && 'disabled'"
                @click="zoomSize(1)"
              />
              <span>{{ nowVal }}%</span>
              <div
                class="zoom-in"
                :class="nowVal == 300 && 'disabled'"
                @click="zoomSize(2)"
              />
            </div>
            <div
              :class="['box-scale', isDisabled ? 'disabledCss' : '']"
              :style="`transform: scale(${nowVal / 100});`"
            >
              <FlowNodeWrap v-model:nodeConfig="nodeConfig" />
              <div class="end-node">
                <div class="end-node-circle"></div>
                <div class="end-node-text">流程结束</div>
              </div>
            </div>
          </section>
        </div>
        <FlowDialogErrorDialog v-model:visible="tipVisible" :list="tipList" />
        <FlowDrawerPromoterDrawer />
        <FlowDrawerApproverDrawer :nodeConfig="nodeConfig" />
        <FlowDrawerConditionDrawer />
        <FlowDrawerCopyDrawer />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { useFlowStore } from "@/stores/flow";
let { setTableId, setIsTried, setFormFiledList, setFormFiledListDiff } =
  useFlowStore();
import {
  flowFormFiledApi,
  addStepApi,
  flowDetailApi,
} from "@/services/api/flow";
const route = useRoute();
let isDisabled = ref(route.query.isDisabled === "1");
let tipList = ref([]);
let tipVisible = ref(false);
let nowVal = ref(100);
let processConfig = ref({});
let nodeConfig = ref({});
let loading = ref(false);
let formFiledList = computed(() => useFlowStore().formFiledList);
/*
 * 初始化流程
 */
const init = () => {
  let data = {
    tableId: route.query.id,
    nodeConfig: {
      nodeName: "发起人",
      nodeId: 100000,
      error: true,
      isAll: false,
      type: 0,
      nodeUserList: [],
      formPermissions: [],
      childNode: null,
      operationInfo: null,
      conditionNodes: null,
      priorityLevel: null,
      conditionList: null,
    },
  };
  processConfig.value = data;
  nodeConfig.value = data.nodeConfig;
  setTableId(data.tableId);
};
/*
 * 获取流程详情
 * @param {Number} id 流程id
 */
const getFlowDetail = () => {
  loading.value = true;
  flowDetailApi(route.query.id)
    .then((res) => {
      if (res.code == 1) {
        const obj = JSON.parse(res.data.flow_raw);
        let list = [...formFiledList.value];
        const permissions = [];
        obj.nodeConfig.formPermissions.forEach((item) => {
          const permission = list.find((u) => u.fieldId == item.fieldId);
          if (permission) {
            permissions.push(item);
          }
        });
        obj.nodeConfig.formPermissions = permissions;
        processConfig.value = obj;
        nodeConfig.value = processConfig.value.nodeConfig;
        setTableId(res.data.id);
      }
      loading.value = false;
    })
    .catch(() => {
      loading.value = false;
    });
};
/*
 * 获取流程表单字段
 * @param {Number} id 表单id
 */
// const getFlowFormFiled = () => {
//   return flowFormFiledApi(route.query.id).then((res) => {
//     if (res.code == 200) {
//       let formFiledList = [];
//       let formFiledListDiff = [];
//       res.data.all_list.forEach((u) => {
//         let obj = {
//           fieldId: u.id,
//           fieldName: u.name,
//           option: u.option,
//           relation: u.relation,
//           type: u.type,
//           readable: true,
//           writable: false,
//         };
//         formFiledList.push(obj);
//       });
//       res.data.diff_list.forEach((u) => {
//         let obj = {
//           fieldId: u.id,
//           fieldName: u.name,
//           option: u.option,
//           relation: u.relation,
//           type: u.type,
//           readable: true,
//           writable: false,
//           is_required: u.is_required,
//         };
//         formFiledListDiff.push(obj);
//       });
//       setFormFiledList(formFiledList);
//       setFormFiledListDiff(formFiledListDiff);
//     }
//   });
// };
/**
 * 保存流程设计
 */
const saveSet = () => {
  setIsTried(true);
  tipList.value = [];
  reErr(nodeConfig.value);
  if (tipList.value.length != 0) {
    tipVisible.value = true;
    return;
  }
  //所有审批路径
  const detailOrder = extractPaths(nodeConfig.value);

  processConfig.value.nodeConfig = nodeConfig.value;
  const flowJson = JSON.stringify(processConfig.value);
  loading.value = true;
  // console.log("flowJson:",flowJson,";detailOrder:",detailOrder);
  addStepApi(route.query.id, flowJson, detailOrder)
    .then((res) => {
      if (res.code == 1) {
        ElMessage({ message: res.msg, type: "success" });
        loading.value = false;
        goBack();
      }
    })
    .catch(() => {
      loading.value = false;
    });
};
/**
 * 获取所有审批流程路径
 */
const extractPaths = (node, path = [], paths = []) => {
  let currentPath = [...path]; // 复制当前路径以避免引用问题

  // 如果当前节点有 nodeId，将其添加到路径(除路由节点)
  if (node.nodeId != null) {
    currentPath.push(node.nodeId);
  }

  // 检查当前节点类型
  if (node.type === 4 && node.conditionNodes) {
    // 如果是路由节点且有条件节点
    let allConditionPaths = []; // 存储所有条件分支生成的路径

    // 遍历所有条件节点
    node.conditionNodes.forEach((condition) => {
      let conditionPath = [...currentPath]; // 创建条件路径
      if (condition.nodeId) {
        conditionPath.push(condition.nodeId); // 添加条件节点ID
      }
      // 递归处理条件子节点
      if (condition.childNode) {
        extractPaths(condition.childNode, conditionPath, allConditionPaths);
      } else {
        // 条件没有子节点，将路径添加到结果中
        allConditionPaths.push(conditionPath);
      }
    });

    // 对于每个条件生成的路径，将路由节点的共有 childNode 添加
    allConditionPaths.forEach((conditionPath) => {
      if (node.childNode) {
        extractPaths(node.childNode, conditionPath, paths);
      } else {
        paths.push(conditionPath);
      }
    });
  } else if (node.childNode) {
    // 存在普通子节点
    extractPaths(node.childNode, currentPath, paths);
  } else {
    // 没有子节点，将当前路径添加到总路径数组
    paths.push(currentPath);
  }

  return paths;
};

const reErr = ({ childNode, nodeUserList, type, isAll }) => {
  if (type == 0 && nodeUserList.length == 0 && !isAll) {
    tipList.value.push({
      name: "发起人",
      type: "发起人",
    });
  }
  if (childNode) {
    let { type, error, nodeName, conditionNodes, nodeUserList } = childNode;
    if (type == 1 || type == 2) {
      // if (error) {
      //   tipList.value.push({
      //     name: nodeName,
      //     type: ["", "经办人", "抄送人"][type],
      //   });
      // }
      if (nodeUserList.length == 0) {
        tipList.value.push({
          name: nodeName,
          type: ["", "经办人", "抄送人"][type],
        });
      }
      reErr(childNode);
    } else if (type == 3) {
      reErr(childNode);
    } else if (type == 4) {
      reErr(childNode);
      for (var i = 0; i < conditionNodes.length; i++) {
        if (conditionNodes[i].error) {
          tipList.value.push({
            name: conditionNodes[i].nodeName,
            type: "条件",
          });
        }
        reErr(conditionNodes[i]);
      }
    }
  } else {
    childNode = null;
  }
};
const zoomSize = (type) => {
  if (type == 1) {
    if (nowVal.value == 50) {
      return;
    }
    nowVal.value -= 10;
  } else {
    if (nowVal.value == 300) {
      return;
    }
    nowVal.value += 10;
  }
};
const goBack = () => {
  window.history.back();
  // return navigateTo("/webapp/flows/list.php");
};

onMounted(async () => {
  // await getFlowFormFiled();
  // flow_raw 1 已有设计流程 0 无设计流程
  if (route.query.flow_raw == 1) {
    getFlowDetail();
  } else {
    init();
  }
});
</script>
<style lang="scss" scoped>
@import "@/assets/css/workflow.css";
.disabledCss {
  pointer-events: none;
  opacity: 0.5;
}
.flow-box {
  position: relative;
  width: 100%;
  .button-back {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 999;
  }
  .button-publish {
    position: absolute;
    top: 10px;
    left: 80px;
    z-index: 999;
  }
  .span-tip {
    position: absolute;
    top: 19px;
    left: 175px;
    z-index: 999;
    color: red;
  }
}
.error-modal-list {
  width: 455px;
}
:deep(.el-card__body) {
  padding: 0;
}
</style>
